package com.xiaohu.transfrom;

import com.xiaohu.bean.WaterSensor;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/*
    富函数与普通的function的区别在于多了一个算子运行前执行方法open()和一个算子结束后执行方法close()

    所有的算子都有一个对应的RichXxxFunction


    注意：
        正常退出【算子执行结束或命令页面中cancel】，close方法会执行，cancel后会close方法执行且也会报错提示
        但是若异常退出【手动，突然宕机】，close方法不会执行



 */
public class RichFunctionDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<WaterSensor> senorDS = env.fromElements(
                new WaterSensor("s1", 1L, 5),
                new WaterSensor("s2", 2L, 2),
                new WaterSensor("s3", 3L, 3),
                new WaterSensor("s1", 4L, 4),
                new WaterSensor("s2", 5L, 5),
                new WaterSensor("s1", 6L, 6)
        );

//       senorDS.filter(new FilterFunction<WaterSensor>() {
//           @Override
//           public boolean filter(WaterSensor value) throws Exception {
//               return "s1".equals(value.getId());
//           }
//       }).print();

       //使用富函数
        senorDS.filter(new RichFilterFunction<WaterSensor>() {

            @Override
            public void open(Configuration parameters) throws Exception {
                System.out.println("我来了。。。。");
            }

            @Override
            public boolean filter(WaterSensor value) throws Exception {
                return "s1".equals(value.getId());
            }

            @Override
            public void close() throws Exception {
                System.out.println("我结束了。。。。");
            }
        }).print();




        env.execute();
    }
}
